﻿using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Mvc.Html;

namespace Backend.JYD.Common
{
    public static class PagerHelper
    {
        /// <summary>
        /// 生成分页HTML
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="page">当前页从1开始</param>
        /// <param name="allpage">总页数</param>
        /// <param name="step">前后幅度</param>
        /// <returns></returns>
        public static MvcHtmlString MultiPager(this HtmlHelper helper, int page, int allpage, int step = 5)
        {
            
            if (allpage <= 0) return new MvcHtmlString("");
            string  qString = helper.ViewContext.HttpContext.Request.QueryString.ToString();
            page = Math.Max(page, 1);
            allpage = Math.Max(allpage, 1);
            var pam = new RouteValueDictionary(helper.ViewContext.RouteData.Values);
            
            string btntpl = "<div  class=\"{0}\"><div class=\"btnleft\"></div><div class=\"btncenter\">{1}</div><div class=\"btnright\"></div> </div>";
            
            StringBuilder pagestr = new StringBuilder();
            if (page == 1)
            {
                pagestr.Append(String.Format(btntpl, "disabled prev",  "<"));
            }
            else 
            {
                pam["page"] = page - 1;
                pagestr.Append(String.Format(btntpl, "prev",  helper.RouteLink("<", pam)));
            }
            int nowspage = 1;
            for (int i = 0; i < step * 2; i++) 
            {
                nowspage = page - step + i;
                pam["page"] = nowspage;
                if (nowspage >= 1 && nowspage <= allpage) {
                    if (nowspage == page)
                    {
                        pagestr.Append(String.Format(btntpl, "current pageNum", helper.RouteLink(nowspage.ToString(), pam)));
                    }
                    else
                    {
                        pagestr.Append(String.Format(btntpl, "pageNum", helper.RouteLink(nowspage.ToString(), pam)));
                    }    
                
                }
            }
            if (nowspage < allpage) {
                pagestr.Append("<div class=\"ellipsis\">&nbsp;</div>");
            }
            if (page == allpage)
            {
                pagestr.Append(String.Format(btntpl, "disabled next", "<"));
            }
            else
            {
                pam["page"] = page + 1;
                pagestr.Append(String.Format(btntpl, "next", helper.RouteLink("<", pam)));
            }
            return new MvcHtmlString( pagestr.ToString());
        }
    }
}
